package com.chj.design.sk;

import java.util.ArrayList;
import java.util.List;

public class Code08_Iterator2 {
	public interface Iterator {
		public boolean hasNext();

		public Object next();
	}// 原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/design_pattern/java_iterator_pattern.html

	public interface Container<T> {
		public void add(T obj);

		public void remove(T obj);

		public Iterator getIterator();
	}// 原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/design_pattern/java_iterator_pattern.html

	public static class NameRepository<T> implements Container<T> {
//		public String names[] = { "Robert", "John", "Julie", "Lora" };

		private List<T> names = new ArrayList<>();

		@Override
		public void add(T obj) {
			// TODO Auto-generated method stub
			names.add(obj);
		}

		@Override
		public void remove(T obj) {
			// TODO Auto-generated method stub
			names.remove(obj);
		}

		@Override
		public Iterator getIterator() {
			return new NameIterator();
		}

		private class NameIterator implements Iterator {

			int index;

			@Override
			public boolean hasNext() {

				if (index < names.size()) {
					return true;
				}
				return false;
			}

			@Override
			public Object next() {

				if (this.hasNext()) {
					return names.get(index++);
				}
				return null;
			}
		}

	}// 原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/design_pattern/java_iterator_pattern.html

	/**
	 * Client类
	 */
//	public class MainClass {

	public static void main(String[] args) {

		NameRepository<String> namesRepository = new NameRepository<String>();
		namesRepository.add("Robert");
		namesRepository.add("John");
		namesRepository.add("Julie");
		namesRepository.add("Lora");

		for (Iterator iter = namesRepository.getIterator(); iter.hasNext();) {
			String name = (String) iter.next();
			System.out.println("Name : " + name);
		} // 原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/design_pattern/java_iterator_pattern.html

	}

//	}
}
